package cn.bellychang.leetcode.question139;

import java.util.*;

/**
 * @author ChangLiang
 * @date 2021/3/12
 */
public class Solution {

    public boolean wordBreak(String s, List<String> wordDict) {

        if (wordDict.contains(s)) {
            return true;
        }

        Queue<Integer> queue = new LinkedList<>();
        queue.offer(0);

        // 加入hashSet是为了去重 比如 s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
        // 可能出现不同的分割情况 导致queue里面的index是相同的

        Set<Integer> visited = new HashSet<>();
        visited.add(0);

        while (!queue.isEmpty()) {
            int curIndex = queue.poll();
            for (int i = curIndex + 1; i <= s.length(); i++) {
                if (visited.contains(i)) {
                    continue;
                }
                if (wordDict.contains(s.substring(curIndex, i))) {
                    if (i == s.length()) {
                        return true;
                    }
                    queue.offer(i);
                    visited.add(i);
                }
            }
        }
        return false;
    }
}
